package com.jhqc.pxsj.msa.sms.provider.service.impl;


import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.jhqc.pxsj.msa.pub.common.ObjectResp;
import com.jhqc.pxsj.msa.pub.common.RespCode;
import com.jhqc.pxsj.msa.sms.api.dto.SmsDTO;
import com.jhqc.pxsj.msa.sms.api.req.AddSendReq;
import com.jhqc.pxsj.msa.sms.api.req.SendSmsKVParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.jhqc.pxsj.msa.sms.api.dto.SmsTemplateDTO;
import com.jhqc.pxsj.msa.sms.provider.config.Constans;
import com.jhqc.pxsj.msa.sms.provider.dao.SmsMapper;
import com.jhqc.pxsj.msa.sms.provider.domain.SmsTemplateDO;
import com.jhqc.pxsj.msa.sms.provider.service.SmsService;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

/**
 * 短信逻辑类
 * @author luochuan
 * @date 2017-04-27
 * @version 1.0
 */
@Service
public class SmsServiceImpl implements SmsService {

	@Autowired
	SmsMapper smsMapper;
	
	
	/**
     * 查询短信模版
     * @param 
     * @return
     */
	@Override
	public List<SmsTemplateDTO> findTemplate() {
		// TODO Auto-generated method stub
		List<SmsTemplateDO> result = smsMapper.findTemplate();
		if ( result == null || result.size() <= 0) {
			return null;
		}
		List<SmsTemplateDTO> smsTemplateDTOs = new ArrayList<SmsTemplateDTO>();
		SmsTemplateDTO dto = null;
		for (SmsTemplateDO smsTemplateDO : result) {
			dto = new SmsTemplateDTO();
			BeanUtils.copyProperties(smsTemplateDO, dto);
			dto.setId(smsTemplateDO.getId());
			dto.setName(smsTemplateDO.getName());
			dto.setTempletId(smsTemplateDO.getTempletId());
			dto.setStatus(smsTemplateDO.getStatus());
			dto.setItem(smsTemplateDO.getItem());
			dto.setContent(smsTemplateDO.getContent());
			smsTemplateDTOs.add(dto);
		}
		return smsTemplateDTOs;
	}

    @Override
    public ObjectResp<SmsDTO> sendCaptcha(AddSendReq req) {
		StringBuilder param ;

		try {
			AlibabaAliqinFcSmsNumSendResponse response = sendCaptcha(req.getMobile() , req.getTemplateId() , req.getItem());
			if (response.isSuccess()){
				return new ObjectResp<SmsDTO>(RespCode.SUCCESS);
			}
			if ("isv.MOBILE_NUMBER_ILLEGAL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：手机号码格式错误");
			}

		} catch (Exception e) {
			return new ObjectResp<SmsDTO>(20000001 , "发送异常");
		}
		return new ObjectResp<SmsDTO>(20000001 , "发送异常");
    }

	@Override
	public ObjectResp<SmsDTO> sendSmsCaptcha(String mobile, String template_id, String item) {
		try {
			AlibabaAliqinFcSmsNumSendResponse response = sendCaptcha(mobile , template_id , item);
			if (response.isSuccess()){
				return new ObjectResp<SmsDTO>(RespCode.SUCCESS);
			}
			if ("isv.OUT_OF_SERVICE".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "业务停机,联系管理员进行充值");
			}
			if ("isv.SMS_TEMPLATE_ILLEGAL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：短信模板不合法");
			}
			if ("isv.SMS_SIGNATURE_ILLEGAL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：签名不合法");
			}
			if ("isv.MOBILE_NUMBER_ILLEGAL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：手机号码格式错误");
			}
			if ("isv.MOBILE_COUNT_OVER_LIMIT".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：手机号码数量超过限制");
			}
			if ("isv.TEMPLATE_MISSING_PARAMETERS".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：短信模板变量缺少参数");
			}
			if ("isv.INVALID_PARAMETERS".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：参数异常检查参数是否合法");
			}
			if ("isv.BUSINESS_LIMIT_CONTROL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：短信验证码频率超出发送次数限制");
			}
			if ("isv.INVALID_JSON_PARAM".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：JSON参数不合法");
			}
			if ("isv.BLACK_KEY_CONTROL_LIMIT".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：模板变量中存在黑名单关键字");
			}
			if ("isv.PARAM_NOT_SUPPORT_URL".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：不支持url为变量");
			}
			if ("isv.PARAM_LENGTH_LIMIT".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：变量长度受限");
			}
			if ("isv.AMOUNT_NOT_ENOUGH".equals(response.getSubCode())){
				return new ObjectResp<SmsDTO>(20000001 , "发送失败：余额不足");
			}

		} catch (Exception e) {
			return new ObjectResp<SmsDTO>(20000001 , "发送异常");
		}
		return new ObjectResp<SmsDTO>(20000001 , "系统繁忙");
	}


	/**
	 * 发送短信到阿里大于
	 * @param mobile
	 * @param template_id
	 * @param
	 * @return
	 * @throws Exception
	 */
	public AlibabaAliqinFcSmsNumSendResponse sendCaptcha(String mobile , String template_id , List<SendSmsKVParam> payload) throws Exception
	{
		String url = Constans.alibaba_gateway_url;
		String sign = Constans.alibaba_sign;
		String appkey = Constans.appid;
		String secret = Constans.appsecret;

		TaobaoClient taobaoClient = new DefaultTaobaoClient(url, appkey, secret);
		AlibabaAliqinFcSmsNumSendRequest request = new AlibabaAliqinFcSmsNumSendRequest();
		request.setExtend("123456");
		request.setSmsType("normal");
		request.setSmsFreeSignName(sign);

		JSONObject jsonObject = new JSONObject();
		for (SendSmsKVParam sendSmsKVParam:payload) {
			jsonObject.put(sendSmsKVParam.getKey() , sendSmsKVParam.getValue());
		}

		String param = JSONObject.toJSONString(jsonObject);
		System.out.println(param);

		request.setSmsParamString(param);
		request.setRecNum(mobile);
		request.setSmsTemplateCode(template_id);
		AlibabaAliqinFcSmsNumSendResponse rsp = taobaoClient.execute(request);

		return rsp;
	}

    /**
     * 发送短信到阿里大于
     * @param mobile
     * @param template_id
     * @param item
     * @return
     * @throws Exception
     */
	@Override
    public AlibabaAliqinFcSmsNumSendResponse sendCaptcha(String mobile , String template_id , String item) throws Exception
    {
        String url = Constans.alibaba_gateway_url;
        String sign = Constans.alibaba_sign;
        String appkey = Constans.appid;
        String secret = Constans.appsecret;

        TaobaoClient taobaoClient = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest request = new AlibabaAliqinFcSmsNumSendRequest();
        request.setExtend("123456");
        request.setSmsType("normal");
        request.setSmsFreeSignName(sign);

        JSONObject payload = JSONObject.parseObject(item);
        String param = JSONObject.toJSONString(payload);
        System.out.println(param);
        
        
        request.setSmsParamString(param);
        request.setRecNum(mobile);
        request.setSmsTemplateCode(template_id);
		AlibabaAliqinFcSmsNumSendResponse rsp = taobaoClient.execute(request);

		return rsp;
    }

	
    
}
